package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

@WebServlet("/ShowCGIVariablesServlet")
public class ShowCGIVariablesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public ShowCGIVariablesServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		//
		String[][] variables = {
				{"AUTH_TYPE", request.getAuthType()},
				{"CONTENT_LENGTH", String.valueOf(request.getContentLength())},
				{"CONTENT_TYPE", request.getContentType()},
				{"DOCUMENT_ROOT", request.getContentType()},
				{"PATH_INFO", request.getPathInfo()},
				{"PATH_TRANSLATED", request.getPathTranslated()},
				{"QUERY_STRING", request.getQueryString()},
				{"REMOTE_ADDR", request.getRemoteAddr()},
				{"REMOTE_HOST", request.getRemoteHost()},
				{"REMOTE_USER", request.getRemoteUser()},
				{"REQUEST_METHOD", request.getMethod()},
				{"SCRIPT_NAME", request.getServletPath()},
				{"SERVER_NAME", request.getServerName()},
				{"SERVER_PORT", String.valueOf(request.getServerPort())},
				{"SERVER_PROTOCOL", request.getProtocol()},
				{"SERVER_SOFTWARE", getServletContext().getServerInfo()}
		};
		
		//
		String title = "Servlet Example: Showing CGI Variables in Servlet";
		out.println(Constants.docType + ServletUtilities.headWithTitle(title) +
				"<body><h1>" + title + "</h1><table border=1><tr bgColor=\"#ffad00\">" + 
				"<th>CGI Variable Name</th><th>Value</th></tr>"
				);
		for(int i = 0 ; i < variables.length ; ++i){
			String varName = variables[i][0];
			String varValue = variables[i][1];
			if(null == varValue){
				varValue = "<em>Not Specified</em>";
			}
			out.println("<tr><td>" + varName + "</td><td>" + varValue + "</td></tr>");
		}
		//
		out.println("</table></body></html>");
				
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private static final Logger logger = 
			Logger.getLogger(ShowCGIVariablesServlet.class);

}
